#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#include <math.h>

void formatFileSize(uint64_t size, char **formattedSize)
{
    static const char *units[] = { "bytes", "KB", "MB", "GB", "TB", "PB", "EB" };   // 64位无符号整数最大只能装到EB

    if(size > 0)
    {
        int digitGroups = 0;
        for(uint64_t i = size / 1024; i > 0 && digitGroups < sizeof(units)/sizeof(units[0])-1; i /= 1024)
            digitGroups++;
        if(asprintf(formattedSize, "%.2f %s", size/pow(1024, digitGroups), units[digitGroups]) < 0)
        {
            *formattedSize = NULL;
            return;
        }

        // 消去不必要的0和小数点
        char *lastDot = strchr(*formattedSize, '.');
        if(lastDot)
        {
#if 1
            if(lastDot[2] == '0')
            {
                int offset = 2;
                int len = strlen(lastDot);
                if(lastDot[1] == '0')
                    offset = 0;
                for(int i = offset; i < len-2+offset; i++)
                {
                    // printf("%c = %c\n", lastDot[i], lastDot[i+3-offset]);
                    lastDot[i] = lastDot[i+3-offset];
                }
            }
#else
            if(lastDot[1] == '0' && lastDot[2] == '0')
            {
                int len = strlen(lastDot);
                for(int i = 0; i < len - 2; i++) lastDot[i] = lastDot[i+3];
            }
            else if(lastDot[2] == '0')
            {
                int len = strlen(lastDot);
                for(int i = 2; i < len; i++) lastDot[i] = lastDot[i+1];
            }
#endif
        }
    }
    // 处理文件大小为0字节的情况
    else if(asprintf(formattedSize, "0 byte") < 0)
        *formattedSize = NULL;

    return;
}

int main(int argc, const char **argv)
{
    char *zSize;
    if(argc != 2)
        return -1;

    formatFileSize(atoll(argv[1]), &zSize);
    printf("%s\n", zSize);
    if(zSize) free(zSize);

    return 0;
}
